#########################################################################
#
#  Copyright (2017, ) Institute of Software, Chinese Academy of Sciences
#  Copyright (2017, ) Beyondcent Co., Lmt
#
#  Author: wuheng@{otcaix.iscas.ac.cn,beyondcent.com}
#  Date  : 2017/6/11
#
#  /abcsys/subpath?key=value
##########################################################################

from __future__ import print_function
import os
import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer, test as _test
import subprocess
from SocketServer import ThreadingMixIn
import argparse


parser = argparse.ArgumentParser(description='Simple Threaded HTTP server to run abcsys.')
parser.add_argument('--port', metavar='PORT', type=int, nargs='?', default=9000,
                    help='Port to run the server on.')

root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    pass

class MainHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            data = ''
            params = ''
            contentType = 'text/json'
            if self.path.startswith("/abcsys/") and len(self.path.split('?')[0].split('/')) == 3 and len(self.path.split('&')) == 1:
                params_list = self.path.split('?')
                if len(params_list) == 2:
                    params_tmp = params_list[1].split('=')
                    for param in params_tmp:
                        params += '%s ' % param
                    module = params_list[0].split('/')[2]
                elif len(params_list) == 1:
                    module = self.path.split('/')[2]
		else:
		    module = "error"
	
		if os.path.exists(root + "/devops-abcsys/modules/" + module):
                    output = subprocess.Popen(
                        root + "/devops-abcsys/modules/" + module + ' %s' %params,
                        shell = True,
                        stdout = subprocess.PIPE)
                    data = output.communicate()[0]
		else:
	            data = '{\"status\":\"500\"}'		
            else:
                data = '{\"status\":\"500\"}'
            self.send_response(200)
            self.send_header('Content-type', contentType)
            self.end_headers()
            self.wfile.write(data)

        except:
	    data = '{\"status\":\"500\"}'
            self.send_response(200)
            self.send_header('Content-type', contentType)
            self.end_headers()
            self.wfile.write(data)

if __name__ == '__main__':
    args = parser.parse_args()
    server = ThreadedHTTPServer(('0.0.0.0', args.port), MainHandler)
    print('Starting server, use <Ctrl-C> to stop')
server.serve_forever()
